﻿app.factory('LoginFactory', function ($http, $q) {
    var status = {}; // currently logged in - bool

    // checking on local stroage to set the status of logged in
    if (localStorage.getItem('token')) {
        status.loggedin = true
    } else {
        status.loggedin = false
    }

    // call api - login
    var login = function (user) {
        var def = $q.defer();
        $http({
            method: 'POST',
            url: '/Token',
            data: 'username=' + user.username + '&password=' + user.password + '&grant_type=password',
            contentType: 'application/x-www-form-urlencoded'
        })
            .success(function (data) {
                localStorage.setItem('token', data.access_token);
                status.loggedin = true;
                def.resolve(data);
            })
            .error(function () {
                logout();
                def.reject();
            });
        return def.promise;
    }

    // Log user out
    var logout = function () {
        localStorage.removeItem('token');
        status.loggedin = false;
    }

    // Get user info on login
    var getInfo = function () {
        var def = $q.defer();
        $http({
            method: 'GET',
            url: '/GetInfo',
            //headers: { Authorization: 'Bearer ' + localStorage.getItem('token') }
        })
        .success(function (data) {
            def.resolve(data);
        })
        .error(function (data) {
            def.reject(data);
        })
        return def.promise;
    }

    // User methods
    return {
        login: login,
        logout: logout,
        getInfo: getInfo,
        status: status
    }


})